//
//  MeInfoController.m
//  ai2ban
//
//  Created by Heartbeats on 2018/1/7.
//  Copyright © 2018年 mac book pro. All rights reserved.
//

#import "MeInfoController.h"
#import "LSXAlertInputView.h"
#import "CityPickerVeiw.h"
#import "ValuePickerView.h"
#import "AddressController.h"


@interface MeInfoController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *userHeadImgV;
@property (weak, nonatomic) IBOutlet UILabel *nameLab;
@property (weak, nonatomic) IBOutlet UILabel *phoneLab;
@property (weak, nonatomic) IBOutlet UILabel *sexLab;
@property (weak, nonatomic) IBOutlet UILabel *addressLab;
@property (weak, nonatomic) IBOutlet UILabel *goodAddressLab;

@property (nonatomic, strong) NSData *imageData;

@end

@implementation MeInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置";
    self.userHeadImgV.layer.cornerRadius = 25;
    self.userHeadImgV.layer.borderWidth = 2;
    self.userHeadImgV.layer.borderColor = [kWhiteColor CGColor];
    self.userHeadImgV.clipsToBounds = true;
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.mj_w, 60)];
    UIButton *loginOutBtn = [[UIButton alloc] initWithFrame:CGRectMake(32, 6, self.view.mj_w - 64, footView.mj_h - 12)];
    [loginOutBtn addTarget:self action:@selector(loginOut:) forControlEvents:UIControlEventTouchUpInside];
    loginOutBtn.layer.cornerRadius = 12;
    loginOutBtn.clipsToBounds = true;
    loginOutBtn.backgroundColor = mainColor;
    [loginOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [footView addSubview:loginOutBtn];
    self.tableView.tableFooterView = footView;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setUserData];
}

-(void) setUserData {
    [self.userHeadImgV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", ImageBaseUrl,[AppManager user].picImg]] placeholderImage:[UIImage imageNamed:@"旅游"]];
    self.nameLab.text = [AppManager user].userName;
    self.phoneLab.text = [AppManager user].telephone;
    self.sexLab.text = [[AppManager user].sex isEqualToString:@"1"] ? @"男" : @"女";
    self.addressLab.text = @"";
    self.goodAddressLab.text = AppManager.user.getDefaultAddress.adressInfo;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [super tableView:tableView numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        UITableViewCell *cell =  [super tableView:tableView cellForRowAtIndexPath:indexPath];
       tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return cell;
    }
      tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0) {
        [self changeHeadImg];
        return;
    }
    if (indexPath.item == 3) {
        ValuePickerView *typePickerView = [[ValuePickerView alloc]init];
        typePickerView.pickerTitle = @"性别";
        typePickerView.dataSource = @[@"男", @"女"];
        typePickerView.valueDidSelect = ^(NSString *value){
            self.sexLab.text = value;
            NSDictionary *dict = @{@"userId": AppManager.user.userId, @"sex": [self.sexLab.text containsString:@"男"] ? @"1": @"0"};
            [self updateUserInfo:dict];
        };
        [typePickerView show];
        return;
    }
    if (indexPath.item == 4) {
        AddressController *addressControl = [[AddressController alloc] init];
        [self.navigationController pushViewController:addressControl animated:true];
        return;
    }
    NSString *str = @"";
    switch (indexPath.item) {
        case 1:
            str = @"昵称";
            break;
        case 2:
            str = @"手机号";
            break;
        default:
            break;
    }
    LSXAlertInputView * alert=[[LSXAlertInputView alloc]initWithTitle:str PlaceholderText:[NSString stringWithFormat:@"请输入%@", str] WithKeybordType:LSXKeyboardTypeDefault CompleteBlock:^(NSString *contents) {
        if (!(contents.length > 0)) {
            return;
        }
        NSDictionary *dict;
        if ([str isEqualToString:@"昵称"]) {
            self.nameLab.text = contents;
            dict = @{@"userId": AppManager.user.userId, @"UserName": contents};
        }else {
            self.phoneLab.text = contents;
            dict = @{@"userId": AppManager.user.userId, @"telephone": contents};
        }
        [self updateUserInfo:dict];
    }];
    [alert show];
}

- (void) updateUserInfo:(NSDictionary *)param {
    [[NetworkManager shareNetwork] requestWithURLString:@"app/system/editInfo" parameters:param method:@"POST" callBack:^(id responseObject) {
        if ([responseObject[@"state"] intValue]) {
            [MozTopAlertView showWithType:MozAlertTypeSuccess text:@"修改成功" parentView:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:UpdateUserDataNotification object:nil];
            return;
        }
        [MozTopAlertView showWithType:MozAlertTypeSuccess text:@"修改失败" parentView:nil];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0 && indexPath.section == 0) {
        return 85;
    }
    return 55;
}

-(void) uploadImage {
    [[NetworkManager shareNetwork] uploadImageFile:self.imageData fileName:@"picImg.png" url:@"uploads/product" callBack:^(id responseObject) {
        if ([responseObject[@"code"] intValue]) {
            NSDictionary *dict = @{@"userId": AppManager.user.userId, @"picImg": responseObject[@"data"]};
            [self updateUserInfo:dict];
            return;
        }
        [MozTopAlertView showWithType:MozAlertTypeSuccess text:@"修改失败" parentView:nil];
    }];
}
- (void)changeHeadImg {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImgByLibrary];
    }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self seleImgByCamera];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void) seleImgByCamera {
    UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
    PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
    PickerImage.allowsEditing = YES;
    PickerImage.delegate = self;
    [self presentViewController:PickerImage animated:YES completion:nil];
}

- (void) selectImgByLibrary {
    UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
    PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    PickerImage.allowsEditing = YES;
    PickerImage.delegate = self;
    [self presentViewController:PickerImage animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self.userHeadImgV setImage:newPhoto];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *newImg = [AppManager scaleToSize:newPhoto size:CGSizeMake(400, 400)];
    self.imageData = UIImageJPEGRepresentation(newImg,1.0f);
    
    [self uploadImage];
}

- (void)loginOut:(UIButton *)sender {
    [AppManager loginOut];
    [[NSNotificationCenter defaultCenter] postNotificationName:UpdateUserDataNotification object:nil];
    [self.navigationController popViewControllerAnimated:true];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
